/**
 * Copyright (c) 1992-2012
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: GenericService.java 2012-06-07 Ashton.J $
 */
package org.ashton.mybatis.base;

import java.io.Serializable;
import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.ashton.mybatis.page.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;


/**
 * 泛型Service实现<p>
 * 
 * @author  Ashton.J
 * @version v1.0
 * 
 * @param <T>  实体类型
 * @param <PK> 主键类型
 */
public abstract class GenericService<T, PK extends Serializable> implements BaseService<T, PK> {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 取得子类Mapper，继承类实现
     * @return
     */
    public abstract BaseMapper<T, PK> getMapper();

    @Override
    public T get(PK id) {
        return getMapper().get(id);
    }

    @Transactional
    @Override
    public void insert(T newInstance) {
        getMapper().insert(newInstance);
    }

    @Transactional
    @Override
    public void update(T transientObject) {
        getMapper().update(transientObject);
    }

    @Transactional
    @Override
    public void delete(PK pk) {
        getMapper().delete(pk);
    }

    @Override
    public Page<T> getPage(Page<T> page) {

        Assert.notNull(page, "page不能为空！");

        if (page.isAutoCount()) {
            long totalCount = (Long) getMapper().getPageCount(page);
            page.setTotalCount(totalCount);
        }

        List<T> result = getMapper().getPageList(page, getRowBounds(page));
        page.setResult(result);

        return page;
    }
    
    private RowBounds getRowBounds(Page<T> page) {
        int offset = page.getPageSize() * (page.getPageNo() - 1);
        int limit = page.getPageSize();

        return new RowBounds(offset, limit);
    }

}
